package com.fy.proj5_permission_transaction_cache.controller;

import com.fy.proj5_permission_transaction_cache.model.User;
import com.fy.proj5_permission_transaction_cache.service.UserService;
import com.fy.proj5_permission_transaction_cache.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 * 提供用户相关的REST API接口
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户列表（简化版，不分页）
     */
    @GetMapping
    public Map<String, Object> getAllUsers() {
        try {
            List<User> users = userService.findAllUsers();
            return ResponseUtil.success(users);
        } catch (Exception e) {
            return ResponseUtil.error(500, "获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 为用户分配角色（保留设置用户角色功能）
     */
    @PostMapping("/{userId}/roles")
    public Map<String, Object> assignRolesToUser(@PathVariable Long userId, 
                                                     @RequestBody List<Long> roleIds) {
        try {
            boolean result = userService.assignRolesToUser(userId, roleIds);
            if (result) {
                return ResponseUtil.success("角色分配成功");
            }
            return ResponseUtil.error(400, "角色分配失败");
        } catch (Exception e) {
            return ResponseUtil.error(500, "角色分配失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户及其角色信息
     */
    @GetMapping("/{id}/roles")
    public Map<String, Object> getUserWithRoles(@PathVariable Long id) {
        try {
            User user = userService.findUserWithRoles(id);
            if (user == null) {
                return ResponseUtil.error(404, "用户不存在");
            }
            return ResponseUtil.success(user);
        } catch (Exception e) {
            return ResponseUtil.error(500, "获取用户角色信息失败: " + e.getMessage());
        }
    }
}